<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-input @clear="clear" v-model="queryInfo.query" clearable placeholder="请输入内容">
        <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <!-- 添加用户区域 -->
      <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
      <!-- 用户列表 -->
      <el-table border stripe :data="userList">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch @change="userStatechange(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="194px">
          <template v-slot="scope">
            <!-- 修改 -->
            <!-- 因为这里需要拿到id的值，所以需要把scope传入 -->
            <!-- 所以不能直接将editDialogVisible设置为true -->
            <el-button
              @click="showEditDialog(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除 -->
            <el-button
              @click="deleteUser(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip :enterable="false" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        @close="addDialogClosed"
        title="请添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
      >
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <el-dialog
        @close="editDialogClosed"
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <!-- 内容主体区域 -->
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button @click="editUser" type="primary">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱地址'))
      }
    }
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18(0-9)|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    return {
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示几条
        pagesize: 5
      },
      // 从后端获取的数据
      userList: [],
      total: 0,
      // dialog的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 请求用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      }
      // 获取成功后就保存数据
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听分页器的尺寸的改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 在上面代码中只是改变了数据，但是页面并没有重新被渲染
      // 所以还需要重新请求数据
      this.getUserList()
    },
    // 监听页码改变的值
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      // 同handleSizeChange一样，需要重新请求数据
      this.getUserList()
    },
    // 监听用户状态发生的改变
    async userStatechange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        // 虽然这里更新失败，但是前端的页面已经更新成功了，所以还要将状态取反
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      } else {
        this.$message.success('更新成功')
      }
    },
    // 清空搜索框，并且重新请求数据
    clear() {
      this.getUserList()
    },
    // 清空添加用户的数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 清空修改用户的数据
    editDialogClosed() {
      console.log(this.$refs.editFormRef)
      console.log(1)
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 因为表单已经使用v-model双向绑定，所以参数直接使用this.addForm即可
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error('添加失败')
          } else {
            this.addDialogVisible = false
            this.getUserList()
            return this.$message.success('添加成功')
          }
        } else {
          return this.$message.error('添加失败')
        }
      })
    },
    // 展示修改用户信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 提交修改
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        console.log(res)
        console.log(2)
        console.log(this.editForm.email)
        if (res.meta.status !== 200) {
          console.log(res.meta.status)
          return this.$message.error('修改失败')
        } else {
          this.editDialogVisible = false
          this.getUserList()
          this.$message.success('修改成功')
        }
      })
    },
    // 删除用户信息
    async deleteUser(id) {
      console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久用户信息, 是否继续?',
        '删除用户信息',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 确定就返回一个confirm字符串
      // 取消就报错，所以上面加了catch捕获错误
      // 加了catch后返回一个cancel字符串
      // 那么现在就可以使用返回的字符串去判断是否删除信息
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消删除')
      } else {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户')
        } else {
          this.getUserList()
          return this.$message.success('删除成功')
        }
      }
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.el-input-group {
  width: 33.33%;
}
.el-button {
  margin-left: 20px;
}
</style>
